package com.sp.scmdb.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.google.common.collect.Lists;

public class ConvertMapToBean {
	@SuppressWarnings("unchecked")
	public static List convertMap(List<Map> list, Class classz) {
		List testList = Lists.newArrayList();
		Field[] filds = classz.getDeclaredFields();
		try {
			for (Map map : list) {
				Object bean = classz.newInstance();
				for (Object obj : map.keySet()) {
					Object key = obj;
					Object value = map.get(obj);
					String columnName = key.toString();
					if (value != null) {
						for (Field field : filds) {
							String fieldName = field.getName();
							if (!fieldName.equalsIgnoreCase(columnName))
								continue;
							Method method = classz.getMethod("set"
									+ fieldName.toString().substring(0, 1)
											.toUpperCase()
									+ fieldName.toString().substring(1),
									new Class[] { field.getType() });
							if (method.getModifiers() != Modifier.PUBLIC)
								continue;
							Object objTmp = null;
							if ("org.joda.time.DateTime".equals(field.getType()
									.getName())) {
								DateTimeFormatter formatter = DateTimeFormat
										.forPattern("yyyy-MM-dd HH:mm:ss");
								if (value.toString().indexOf(".") > 0) {
									objTmp = formatter.parseDateTime(value
											.toString().substring(
													0,
													value.toString().indexOf(
															".")));
								} else {
									objTmp = formatter.parseDateTime(value
											.toString());
								}
							} else {
								objTmp = org.apache.commons.beanutils.ConvertUtils
										.convert(value.toString(), field
												.getType());
							}
							method.invoke(bean, new Object[] { objTmp });
							break;
						}
					}
				}
				testList.add(bean);
			}
		} catch (Exception ex) {
			throw new IllegalStateException("convert bean error !reason:"
					+ ex.getMessage());
		}
		return testList;
	}
}
